import * as bajaService from '@/services/bajaService';
import { SUBSYSTEM_TYPE } from '@/utils/constants';

export default {
  namespace: 'tlsWebServer',
  state: {
    title: '',
    subSystems: []
  },
  reducers: {
    setData(state, { payload: {title, subSystems}}) {
      return { ...state, title, subSystems };
    },
  },
  effects: {
    *fetch({ _ }, { call, put }) {
      let title = '', subSystems=[];
      const tlsWebServer = yield call(bajaService.fetchTlsWebServer);
      if(tlsWebServer) {
        title = tlsWebServer.getTitle();
        const subSystemsRoot = yield call(bajaService.Ord, 'station:|slot:/Services/TLSWebServer/subSystemsRoot');
        if(subSystemsRoot) {
          subSystems = yield call(bajaService.fetchNavChildren, subSystemsRoot);
          if(subSystems) {
            const subSystemList = [];
            for(let i=0; i<subSystems.length; i++) {
              const subSystem = subSystems[i];
              const displayName = subSystem.getDisplayName().trim().replace(' ', '$20');
              // console.log("subSystem", subSystem, displayName);
              const { $ordinal } = subSystem.getSubSystemType();
              const modulesRoot = yield call(bajaService.Ord, 'station:|slot:/Services/TLSWebServer/subSystemsRoot/' + displayName + '/modulesRoot');
              subSystem.modules = [];
              if(modulesRoot) {
                const modules = yield call(bajaService.fetchNavChildren, modulesRoot);
                if(modules) {
                  subSystem.modules = modules.map((module=> module.$handle));
                }
              }
              subSystemList.push({
                $handle: subSystem.$handle,
                $typeSpec: subSystem.getType().$typeSpec,
                title: subSystem.getTitle(),
                url: subSystem.getUrl(),
                subSystemType: SUBSYSTEM_TYPE[$ordinal],
                navOrd: subSystem.getNavOrd().toString(),
                pagePath: subSystem.getPagePath(),
                modules: subSystem.modules
              });
            }
            subSystems = subSystemList;
          } else {
            subSystems = []
          }
        }
      }
      console.log("fetch()", subSystems);
      yield put({ type: 'setData', payload: {
        title, subSystems
      }});
    }
  },
  subscriptions: {
    setup({ dispatch, history }) {
      return history.listen(({ pathname }) => {
        if (pathname === '/') {
          console.log("listen()");
          dispatch({ type: 'fetch'});
        }
      });
    },
  },
}
